package com.zhtools.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class IDCardUtils {
    private static final String REGX_18 = "^(\\d{6})(\\d{4})(\\d{2})(\\d{2})(\\d{3})([0-9]|X)$";
    private static final String ERROR_IDCARDNO = "错误的身份证号码";

    /**
     * 验证身份证号码是否合法
     *
     * @param idCardNo
     * @return
     */
    public static boolean isIDCardNo(String idCardNo) {
        Pattern pattern = Pattern.compile(REGX_18);
        Matcher matcher = pattern.matcher(idCardNo);
        return matcher.matches();
    }

    /**
     * 获取出生年份
     *
     * @param idCardNo
     * @return
     */
    public static String getBirthYear(String idCardNo) {
        if (!isIDCardNo(idCardNo)) {
            throw new IllegalArgumentException(ERROR_IDCARDNO);
        }
        return idCardNo.substring(6, 10);
    }

    /**
     * 获取出生月份
     * @param idCardNo
     * @return
     */
    public static String getBirthMonth(String idCardNo) {
        if (!isIDCardNo(idCardNo)) {
            throw new IllegalArgumentException(ERROR_IDCARDNO);
        }
        return idCardNo.substring(10, 12);
    }

    /**
     * 获取出生日期
     * @param idCardNo
     * @return
     */
    public static String getBirthDay(String idCardNo) {
        if (!isIDCardNo(idCardNo)) {
            throw new IllegalArgumentException(ERROR_IDCARDNO);
        }
        return idCardNo.substring(12, 14);
    }

    /**
     * 获取年龄
     *
     * @return
     */
    public static Integer getAge(String idCardNo) {
        if (!isIDCardNo(idCardNo)) {
            throw new IllegalArgumentException(ERROR_IDCARDNO);
        }
        Integer birthYear = Integer.parseInt(getBirthYear(idCardNo));
        Integer currentYear = DateUtils.getCurrentYear();
        return currentYear - birthYear;
    }
}
